<template>
  <div class="search">
    <form action="/">
      <van-search
        background="#3296fa"
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isShowRes = false"
      />
    </form>

    <search-results v-if="isShowRes" :searchText="value" />
    <search-history @clear="history = []" v-else-if="!value" :history="history" @onSearch="onSearch" />
    <search-suggestion :searchText="value" v-else @on-search="onSearch" />
  </div>
</template>

<script>
import SearchHistory from './components/SearchHistory.vue'
import SearchResults from './components/SearchResults.vue'
import SearchSuggestion from './components/SearchSuggestion.vue'
import { setStorage, getStorage } from '@/utils/storage.js'
export default {
  components: { SearchHistory, SearchResults, SearchSuggestion },
  data () {
    return {
      value: '',
      isShowRes: false,
      history: getStorage('TT-HISTORY') || [] // 用来存储搜索历史 优先使用本地存储，如果本地没有值，将返回null，此时再用运算符使其等于空数组[]
    }
  },

  watch: {
    history: {
      deep: true,
      handler (val) { // val是变化为的新值
        setStorage('TT-HISTORY', val)
      }
    }
  },

  created () {

  },

  methods: {
    onSearch (val) {
      this.value = val // 加上这一步对原方法没有影响，但这样就和suggestionSearch一样就能调用同一个了
      this.isShowRes = true

      // 进行搜索历史的存储
      this.history.unshift(val)
      this.history = [...new Set(this.history)]
    },
    onCancel () {
      console.log(333)
    }
    // suggestionSearch () { // 和上面的ononSearch一样，直接两个合并，调用同一个就好
    //   this.value = val
    //   this.isShowRes = true
    // }
  }
}
</script>

<style scoped lang='less'>
.search {
  .van-search__action {
    color: #fff;
  }
}
</style>
